
import _mysql
import logger
import hashlib

class DbHandler:
	##
	## Ansluter till databas of verifierar att tabellerna finns. 
	##  Om de inte finns, skapa dem..
	##
	def __init__(self, pSettings):
		# Connect to database:
		try:
		    self.db=_mysql.connect(host=pSettings.host, user=pSettings.username, passwd=pSettings.password, db=pSettings.schema)

		    # Verifiera att tabeller finns.
		    self.db.query("SELECT * FROM project LIMIT 1")
		    self.db.use_result();
		    self.db.query("SELECT * FROM log LIMIT 1")
		    self.db.use_result();
		    self.db.query("SELECT * FROM metric LIMIT 1")
		    self.db.use_result();

		    return None;
		except _mysql.Error, e:
		    if e.args[0] == 1146:
			# Skapa tabell
			logger.printerror("No tables found. Create tables first!")
			logger.printerror("The SQL code to create tables is in sql/tables.sql")
			exit();

		    if e.args[0] == 2005:
			logger.printerror("Fel: Kunde inte ansluta till: "+pHost)
			exit();

		    if e.args[0] == 1045:
			logger.printerror("[E] Invalid username/password!"+pHost)
			exit();

		    if e.args[0] == 1049:
			logger.printerror("[E] The schema doesnt exists!\r\nCreate it in mysql first.")
			exit();

		    else:
			logger.printerror("[E] Error %d: %s" % (e.args[0],e.args[1]))
			exit();

	# Insert project to database
	def insertproject(self, name, type):
		try:
			self.db.query("insert into project (name, type) VALUES ('"+name+"','"+type+"')")
		except _mysql.Error, e:
		    if e.args[0] == 1062:
			logger.printinfo("[!] Projektet "+name+" finns redan, analyzerar det igen!")
		    else:
			logger.printerror("[E] Error %d: %s" % (e.args[0],e.args[1]))
			return;
	
	# Insert to scmlog
	def insertscmlog(self, project, url, rev, user, date):
			# Insert into database and notify user.
			try:
				self.db.query("insert into log (project, url, rev, user, date) VALUES ('"+project+"','"+url+"','"+rev+"','"+user+"','"+date+"')")
				logger.printinfo("New revision "+rev)
			except _mysql.Error, e:
		    		if e.args[0] != 1062: # Ignorerar duplicate fel.
					print "Error %d: %s" % (e.args[0],e.args[1])

	def fetchrevisonstoanalyze(self, project, url):
		# Get the first revision each month and check if its been analyzed!
		self.db.query("select revs.foundrev as rev, (Select 1 from metric where metric.rev=revs.foundrev and revs.url=metric.url and revs.project=metric.project limit 1) as analyzed from (SELECT log.url,log.project, ( select c.rev from log as c where c.project=log.project and c.date= min(log.date) limit 1) as foundrev FROM `log` where project='"+project+"' and url='"+url+"' group by date_format(date,'%Y%m') order by date desc) as revs")  
		r = self.db.store_result()
		revisions = r.fetch_row(10000)

		revs = []
		for row in revisions: 
		        revision = row[0]
			analyzed = row[1]

			if(analyzed is None):
				revs.append(revision)

		return revs
		
	# Insert metric
	def insertmetric(self, project, revision, url, files, blank, comment, code):
		self.db.query("insert into metric (files, blank, comment, code, rev, url, project) VALUES ('"
					+files+"','"+blank+"','"+comment+"','"+code+"','"+revision+"','"+url+"','"+project+"')");

	# Insert filemetric
	def insertfilemetric(self, project, revision, url, filename, blank, comment, code, lang):
		try:
			# Because of the limited key size in mysql, Generate a md5 hash as filename id:
			md5name = hashlib.md5( filename ).hexdigest();
			self.db.query("insert into filemetric (project, rev,url, file, blank, comment, code, lang, md5) VALUES ('"
				+project+"','"+revision+"','"+url+"','"+filename+"','"+blank+"','"+comment
				+"','"+code+"','"+lang+"','"+md5name+"')");
		except UnboundLocalError, e:
			print e
		except _mysql.Error, e:	
			print "Error %d: %s" % (e.args[0],e.args[1])





	
